<?php

require_once("../accesscheck.php");
require_once("../utils/pui_content_table_renderer.php");

if( isset($_POST['delsites']) ) {
	
	for($i = 1; ; $i++ ) {
		// if the site id has not been defined then we've run out of data
		if( !isset($_POST['id' . $i]) ) {
			break;
		}
		
		// else try to delete the site information from the users_sites table
		$site = $_POST['id' . $i];
		$user = $_POST['user'];
		$deleteSQL = "DELETE FROM users_sites WHERE Site = $site AND User = $user";
		$result = mysqli_query($config,$deleteSQL) or die(mysqli_error());
	}
}

if( isset($_POST['addsites']) ) {
	for($i = 1; ; $i++ ) {
		// if the site id has not been defined then we've run out of data
		if( !isset($_POST['id' . $i]) ) {
			break;
		}
		
		// else try to delete the site information from the users_sites table
		$site = $_POST['id' . $i];
		$user = $_POST['user'];
		$date = date('Y-m-d');
		
		$query = "SELECT * FROM users_sites WHERE User = $user AND Site = $site";
		$rsQuery = mysqli_query($config,$query);
		$totalRows = mysqli_num_rows($rsQuery);
		
		if( $totalRows == 0 ) {
			mysqli_free_result($rsQuery);
			$insertSQL = "INSERT INTO users_sites (User,Site,DateModified) VALUES($user,$site,'$date') ";
			$result = mysqli_query($config,$insertSQL) or die(mysqli_error());
		} else {
			mysqli_free_result($rsQuery);
		}
	}
}

if( isset($_POST['changepass']) ) {
	$old = $_POST['old'];
	$new = $_POST['new'];
	$user = $_POST['user'];
	
	$selectSQL = "SELECT * FROM users WHERE id = $user";
	$rsUser = mysqli_query($config,$selectSQL);
	$row_rsUser = mysqli_fetch_assoc($rsUser);
	$rows = mysqli_num_rows($rsUser);
	
	if( $rows == 0 ) {
		echo "Could Not Find User To Change Information For";	
		exit;
	}
	
	$oldPassHash = $row_rsUser['Password'];
	$oldSalt = $row_rsUser['PassSalt'];
	$confirmOldHash = md5( $old . $oldSalt );
	
	// release old result set
	mysqli_free_result($rsUser);
	
	// confirm that the supplied password is a valid
	if( $confirmOldHash != $oldPassHash ) {
		echo "The Old Password Supplied Is Not Valid. Please Check and Correct";	
		exit;
	}
	
	$newSalt = rand(1,100000);
	$newPassHash = md5( $new . $newSalt );
	
	// update the user account with the new password hash and salt
	$updateSQL = "UPDATE users SET `Password` = '$newPassHash', `PassSalt` = '$newSalt' WHERE id = $user";
	$result = mysqli_query($config,$updateSQL) or die(mysqli_error());
	
	echo "Password Change Successful";
}

/**
 * The following code works with the new user interface
 */
$action = isset($_POST['action']) ? $_POST['action'] : "";
$manager = new UserManager();
$renderer = new ContentTableRenderer("Users");
$renderer->setItemsTitle("System Users");

switch($action) {
    
    case 'load_items':
        $category_id = intval($_POST['category']);
        $limit = intval($_POST['limit']);
        $start = isset($_POST['start']) ? $_POST['start'] : 0;
        $role = $manager->getUserRole($category_id);
        $users = $role->getUsers($start, $limit); // start, limit

        // get the total number of articles in this category and set that as the
        // the total content count for this load
        $renderer->setTotalItemsCount($role->getUserCount());

        $itemData = array();

        for ($i = 0; $i < count($users); $i++) {
            array_push($itemData, array(
                "title" => $users[$i]->getData('FirstName') . ' ' . $users[$i]->getData('LastName'),
                "id" => $users[$i]->getId(),
                //"url" => $users[$i]->getURL(),
                "published" => $users[$i]->isActivated(),
                "last_access" => $users[$i]->getLastAccessDate('jS F, Y')
            ));
        }

		$renderer->setItemsTitle("Users");
        $renderer->setItemsArray($itemData);
        $renderer->addColumn( array('header' => 'Last Access', 'field' => 'last_access'));
        $renderer->render();
        break;
        
        
    case 'publish_item':
        $manager->publishItem($_POST['item_id'], $_POST['publish'] == "true");
        break;
    
    case 'delete_category':
        $manager->deleteCategory($_POST['category_id']);
        break;

    case 'delete_items':
        $manager->deleteItems(explode(",", $_POST['item_ids']));
        break;
    
    case 'move_items':
        $ids = $_POST['item_ids'];
        $category_id = $_POST['category_id'];
        $manager->moveItems(explode(",", $ids), $category_id);
        break;
    
    case 'load_editor':
        include('../forms/users_form.php');
        break;
    
    case 'update_user':
		$manager->updateUser();
        break;
		
	case 'add_user':
		$manager->addUser();
		break;
}
?>